﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;

namespace ThinkDotNetEngine.Bots.Ammos
{
    public class CachedAmmoLoader:IAmmoLoader
    {
        private readonly Game _game;
        readonly private Dictionary<AmmoType, string> _mappings =new Dictionary<AmmoType, string>();
        readonly private Dictionary<AmmoType, AmmoBase> _cachedAmmos =new Dictionary<AmmoType, AmmoBase>();

        public CachedAmmoLoader(Game game)
        {
            _game = game;
            _mappings.Add(AmmoType.Plasma,"ammos\\plasma.txt");
            _mappings.Add(AmmoType.Rocket, "ammos\\rocket.txt");
            _mappings.Add(AmmoType.Missile, "ammos\\missile.txt");
        }

        public AmmoBase Load(AmmoType ammoType)
        {
            AmmoBase prototype;
            if (_cachedAmmos.ContainsKey(ammoType))
                prototype = _cachedAmmos[ammoType];
            else
            {
                using(Stream stream=File.Open(_mappings[ammoType],FileMode.Open))
                {
                    XmlSerializer serializer=new XmlSerializer(typeof(AmmoBase));
                    prototype = (AmmoBase) serializer.Deserialize(stream);
                    _cachedAmmos.Add(ammoType, prototype);
                }
            }
            return (AmmoBase)Activator.CreateInstance(prototype.GetType(),_game, prototype);
        }
        public void Save(string path,AmmoBase ammo)
        {
            using (Stream stream = File.Open(path, FileMode.OpenOrCreate))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(AmmoBase));
                serializer.Serialize(stream,ammo);
            }
        }
    }
}
